<template>
  <!-- adminEditAffiliatedCompanies  管理员编辑指定人的单位 -->
  <PageContainer>
    <view class="edit-affiliated-companies">
      <Header :title="`${data ? '编辑' : '新增'}单位`" :is-box-shadow="false" />
      <Box title="单位信息" :warp-m-bottom="0" />
      <view class="firm-info">
        <view class="firm-info_item">
          <text class="firm-info_item--label">单位名称</text>
          <UniEasyinput
            v-model="formData.name"
            type="text"
            :inputBorder="false"
            :clearable="false"
            placeholder="请输入单位名称"
          />
        </view>
        <view class="firm-info_item">
          <text class="firm-info_item--label">单位职务</text>
          <UniEasyinput
            v-model="formData.position"
            type="text"
            :inputBorder="false"
            :clearable="false"
            placeholder="请输入单位职务"
          />
        </view>
        <view class="firm-info_item">
          <text class="firm-info_item--label">单位地址</text>
          <FormSelectAddress v-model="formData.addressStr" :is-border="false" />
        </view>
        <view class="firm-info_item firm-info_upload">
          <view class="firm-info_item--label">
            <text>单位logo</text>
            <text class="label-des">请上传分辨率200*200，2M以内图片</text>
          </view>
          <view class="upload-img">
            <view v-if="formData.logo" class="upload-img_item">
              <view class="logo-img">
                <TImage :src="formData.logo" width="212rpx" height="135rpx" :preview="true" />
              </view>
              <view class="del-icon" @click="delLogo">
                <image class="icon" src="https://hb-saas.obs.cn-south-1.myhuaweicloud.com/mall/saas/icon/del-icon.png" mode="scaleToFill" />
              </view>
            </view>
            <view v-else class="upload-img_item upload-img_add" @click="addLogo">
              <view class="ali-icon">&#xe61f;</view>
              <text>添加图片</text>
            </view>
          </view>
        </view>
      </view>
      <Box title="主营业务" :is-show="showHideItems" :animation-index="1">
        <FormHonor
          v-model="formData.mainBusinessList"
          label="主营业务"
          :tag-flex="true"
          :input-maxlength="10"
          placeholder="例：房地产开发、金融服务、汽车销售、服装生产"
        />
      </Box>

      <Box title="社会荣誉/职务" :is-show="showHideItems" :animation-index="2">
        <FormHonor
          v-model="formData.socialIdentityList"
          :tag-flex="true"
          label="社会荣誉/职务"
          placeholder="例：XX会长单位、XX示范企业、XX驰名品牌、XX高新企业"
        />
      </Box>
      <Box title="简介" :is-show="showHideItems" :animation-index="3">
        <ElegantDemeanour
          v-model="formData.imgList"
          :is-edit="true"
          :card-type="ApplyTypeEnum.UNIT"
        />
        <CuttingLine />
        <UploadVideo v-model="videoInfo" />
        <CuttingLine />
        <CardComHeader title="电子文档" :des="`请上传${fileDefaultSize.doc}M以内文档文件`" />
        <FormUploadFile v-model="document" :limit="9" media-type="doc" />
        <CuttingLine />
        <Introduction
          v-model="formData.introduce"
          :isEdit="true"
          placeholder="文化、品牌、产品、服务、优势等介绍"
          :card-type="ApplyTypeEnum.UNIT"
        />
      </Box>

      <view v-if="!showHideItems" class="unfold" @click="showItems">
        <text>完善更多信息</text>
        <text class="ali-icon">&#xe67e;</text>
      </view>
      <TButtonGroup>
        <TButton class="gutter-btn" text="取消" custom-class="cardBlackBtn" @click="handleCancel" />
        <TButton class="gutter-btn" text="确认" custom-class="cardBtn" @click="submit" />
      </TButtonGroup>
    </view>
  </PageContainer>
</template>

<script lang="ts" setup>
  /**  adminEditAffiliatedCompanies  管理员编辑指定人的单位 */
  import PageContainer from '@/components/PageContainer/index.vue';
  import Header from '@/components/Header/index.vue';
  import { navigateBack, onLoad } from '@/router';
  import { reactive, ref, unref, watch } from 'vue';
  import Box from '../components/box/index.vue';
  import FormHonor from '@/components/Form/components/FormHonor.vue';
  import { ApplyTypeEnum } from '@/enums/membershipEnum';
  import ElegantDemeanour from '../components/elegantDemeanour/index.vue';
  import CuttingLine from '../components/cuttingLine/index.vue';
  import UploadVideo from '../components/uploadVideo/index.vue';
  import Introduction from '../components/introduction/index.vue';
  import CardComHeader from '../components/cardComHeader/index.vue';
  import FormUploadFile from '@/components/Form/components/upload/FormUploadFile.vue';
  import UniEasyinput from '@/uni_modules/uni-easyinput/components/uni-easyinput/uni-easyinput.vue';
  import FormSelectAddress from '@/components/Form/components/FormSelectAddress.vue';
  import { type UnitAddData } from '@/api/mine/types';
  import { Toast } from '@/utils';
  import { fileDefaultSize, useUpload } from '@/hooks/core/useUpload';
  import TButtonGroup from '@/components/TButtonGroup/index.vue';
  import TButton from '@/components/TButtonGroup/TButton.vue';
  import type { FunctionArgs } from '@vueuse/core';
  import { isArrayString } from '@/utils/is';
  import TImage from '@/components/TImage/index.vue';
  import { sysUnitAdd, sysUnitEdit } from '@/api/admin';
  import PrivacyPopup from '@/components/PrivacyPopup/index.vue';

  let success: FunctionArgs;

  const showHideItems = ref(false);

  function showItems() {
    showHideItems.value = true;
  }

  const { result, chooseFile, delResultItem } = useUpload({
    count: 1,
    isCrop: true,
    cropOptions: {
      width: 400,
      height: 400,
    },
  });

  watch(
    result,
    (val) => {
      const item = val[0];
      if (item && item.isSuccess) {
        formData.logo = item.filePath as string;
      }
    },
    { deep: true },
  );

  function addLogo() {
    chooseFile({ mediaType: 'image' });
  }
  function delLogo() {
    delResultItem(0);
    formData.logo = '';
  }

  const videoInfo = ref({
    tempFilePath: '',
    thumbTempFilePath: '',
  });

  const formData = reactive<UnitAddData>({
    name: '',
    logo: '',
    position: '',
    addressStr: '',
    mainBusinessList: [],
    socialIdentityList: [],
    imgList: [],
    introduce: '',
  });

  function submit() {
    if (!userId.value) return;
    const { tempFilePath, thumbTempFilePath } = videoInfo.value;
    if (!formData.name) return Toast('请填写单位名称');
    if (!formData.position) return Toast('请填写单位职务');
    const result: UnitAddData = {
      ...unref(formData),
      video: tempFilePath,
      videoCover: thumbTempFilePath,
      document: document.value?.length ? JSON.stringify(unref(document)) : '',
    };
    if (data.value) {
      /** 编辑 */
      sysUnitEdit({ id: data.value.id as number, appUserInfoId: userId.value, ...result }).then(
        () => {
          Toast({ title: '编辑成功', success: successCallback });
        },
      );
    } else {
      /** 新增 */
      sysUnitAdd({ appUserInfoId: userId.value, ...result }).then(() => {
        Toast({ title: '添加成功', duration: 1500, success: successCallback });
      });
    }
  }

  function successCallback() {
    success?.();
    navigateBack();
  }

  function handleCancel() {
    navigateBack();
  }

  const data = ref<{ id: number } & UnitAddData>();
  const document = ref<string[]>();
  const userId = ref<number>();
  onLoad<'adminEditAffiliatedCompanies'>((op) => {
    success = op.success;
    userId.value = op.userId;
    if (op.item) {
      data.value = op.item;
      const {
        name,
        position,
        logo,
        addressStr,
        mainBusinessList,
        imgList,
        introduce,
        socialIdentityList,
        video,
        videoCover,
        documentName,
        document: itemDocument,
      } = op.item;
      formData.name = name;
      formData.position = position;
      formData.logo = logo;
      formData.addressStr = addressStr;
      formData.mainBusinessList = mainBusinessList;
      formData.introduce = introduce;
      formData.socialIdentityList = socialIdentityList;
      formData.imgList = imgList || [];
      videoInfo.value.tempFilePath = video ?? '';
      videoInfo.value.thumbTempFilePath = videoCover ?? '';
      if (itemDocument) {
        if (isArrayString(itemDocument)) {
          const arr = JSON.parse(itemDocument) as string[];
          document.value = arr.map((v) => v);
        } else {
          document.value = [JSON.stringify({ name: documentName, url: itemDocument })];
        }
      }
      if (
        mainBusinessList?.length ||
        imgList?.length ||
        introduce ||
        socialIdentityList?.length ||
        video ||
        unref(document)?.length
      ) {
        showHideItems.value = true;
      }
    } else {
      document.value = [];
    }
  });
</script>
<style lang="scss">
  .edit-affiliated-companies {
    .firm-info .uni-easyinput,
    .upload-popup .uni-easyinput {
      text-align: right !important;
    }
  }
  .edit-container .uni-easyinput__content-textarea {
    max-height: 600rpx;
  }
</style>
<style lang="scss" scoped>
  .firm-info {
    background-color: #fff;
    margin-bottom: 30rpx;
    &_item {
      padding: 0 30rpx;
      height: 86rpx;
      display: flex;
      align-items: center;
      justify-content: space-between;
      font-size: 27rpx;
      color: #333;
      border-top: 1px solid #f5f5f5;
      &--label {
        min-width: 200rpx;
        text-align: left;
        flex-shrink: 0;
        .label-des {
          font-size: 23rpx;
          color: #808080;
          margin-left: 15rpx;
        }
      }
    }
    &_upload {
      display: block;
      border-bottom: none;
      height: auto;
      padding-top: 30rpx;
      padding-bottom: 30rpx;
      .upload-img {
        margin-top: 30rpx;
        &_item {
          width: 212rpx;
          height: 135rpx;
          background: #f5f5f5;
          border-radius: 10rpx;
          position: relative;
          .logo-img {
            width: inherit;
            height: inherit;
            border-radius: 10rpx;
            overflow: hidden;
          }
          .del-icon {
            width: 50rpx;
            height: 50rpx;
            position: absolute;
            right: -20rpx;
            top: -10rpx;
            text-align: center;
            vertical-align: middle;
            .icon {
              width: 32rpx;
              height: 32rpx;
            }
          }
        }
        &_add {
          display: flex;
          align-items: center;
          justify-content: center;
          flex-direction: column;
          font-size: 27rpx;
          color: #808080;
          .ali-icon {
            font-size: 40rpx;
            margin-bottom: 10rpx;
          }
        }
      }
    }
  }

  .unfold {
    width: 100%;
    height: 100rpx;
    background-color: #fff;
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    font-size: 28rpx;
    color: #999996;
    .ali-icon {
      font-size: 48rpx;
    }
  }
</style>
